package utils

import (
	"fmt"
	"log"

	"github.com/syndtr/goleveldb/leveldb"
)

type Leveldb struct {
	db *leveldb.DB
}

func (w *Leveldb) OpenDB(db_path string) bool {
	db, err := leveldb.OpenFile(db_path, nil)
	if err != nil {
		w.db = nil
		return false
	} else {
		w.db = db
		return true
	}
}

func (w *Leveldb) CloseDB() {
	if w.db != nil {
		w.db.Close()
	}
}

func (w *Leveldb) Get(key string) string {
	if w.db == nil {
		return "Error"
	}

	value, err := w.db.Get([]byte(key), nil)
	if err != nil {
		log.Println(err)
		return "None"
	} else {
		return string(value[:])
	}
}

func (w *Leveldb) Put(key string, value string) error {
	if w.db == nil {
		return fmt.Errorf("Eoor")
	} else {
		return w.db.Put([]byte(key), []byte(value), nil)
	}
}

func (w *Leveldb) Delete(key string) error {
	if w.db == nil {
		return fmt.Errorf("Eoor")
	} else {
		return w.db.Delete([]byte(key), nil)
	}
}
